// 从 output/坐骑训练经验.csv 同步 exp_per_training 到 mount_level_experience（按 level 匹配）
const fs = require('fs');
const path = require('path');
const { createPool } = require('mysql2/promise');

function parseCsv(filePath) {
    const raw = fs.readFileSync(filePath, 'utf8');
    const lines = raw.split(/\r?\n/).filter(l => l.trim().length > 0);
    const rows = [];
    for (let i = 1; i < lines.length; i++) { // 跳过表头
        const cols = lines[i].split(',');
        const level = Number(cols[0]);
        const exp = Number(cols[1]);
        if (Number.isFinite(level) && Number.isFinite(exp)) rows.push({ level, expPerTraining: exp });
    }
    return rows;
}

async function main() {
    const csvPath = path.resolve(process.cwd(), 'output/坐骑训练经验.csv');
    if (!fs.existsSync(csvPath)) {
        console.error(`未找到CSV: ${csvPath}`);
        process.exit(1);
    }
    const data = parseCsv(csvPath);
    if (!data.length) {
        console.error('CSV解析为空');
        process.exit(1);
    }

    const host = process.env.DB_HOST || '43.143.253.188';
    const port = Number(process.env.DB_PORT || 3306);
    const user = process.env.DB_USER || 'nextjs';
    const password = process.env.DB_PASS || 'yEAiRE2jcxTyRBy5';
    const database = process.env.DB_NAME || 'nextjs';

    const pool = await createPool({ host, port, user, password, database, multipleStatements: true });
    const conn = await pool.getConnection();
    try {
        await conn.beginTransaction();
        let affected = 0;
        for (const r of data) {
            const [res] = await conn.query(
                'UPDATE mount_level_experience SET exp_per_training = ? WHERE level = ?',
                [r.expPerTraining, r.level]
            );
            affected += (res && res.affectedRows) ? res.affectedRows : 0;
        }
        await conn.commit();
        console.log(`✅ 已更新 ${affected} 行 exp_per_training`);
    } catch (e) {
        await conn.rollback();
        console.error('❌ 更新失败:', e.message);
        process.exit(1);
    } finally {
        conn.release();
        await pool.end();
    }
}

main().catch(err => { console.error(err); process.exit(1); });



